#######################################
######Masculinity Threat Analysis######
#######################################
###############10/10/25##################
#######################################

####Analysis Script for Gothreau & Haas, forthcoming in Journal of Experimental Political Science###
####A Replication and Extension of Willer et al. (2013) Overdoing Gender: A Test of the Masculine Overcompensation Thesis###

library(haven)
library(ggplot2)
library(dplyr)
library(tableone)
library(cobalt)
library(kableExtra)
library(flextable)

#Set Working Directory#
MTData <- read.csv("CleanMTData.csv")

####Balance Table#####

# Demographic Variables 

MTData$gender_binary <- factor(MTData$Q_CDGDRDESC_17, levels = c("1", "2"), labels = c("Men", "Women"))
MTData$PID_binary <- factor(MTData$PartyID5, levels = c("1", "2", "4", "5"), labels = c("Democrat", "Democrat", "Republican", "Republican"))
MTData$race_binary <- factor(MTData$RACETHNICITY, levels = c("1", "2", "3", "4", "5", "6"), labels = c("White", "Non-White", "Non-White", "Non-White", "Non-White", "Non-White"))

#age, education, income

# Specify variables
vars <- c("AGE", "EDUC5", "INCOME", "gender_binary", "PID_binary", "race_binary")
factorVars <- c("gender_binary", "PID_binary", "race_binary")

# Create the table
table1 <- CreateTableOne(vars = vars, strata = "P_EXP", data = MTData, factorVars = factorVars)

# Print with p-values
print(table1, showAllLevels = TRUE, quote = FALSE, noSpaces = TRUE, pDigits = 3, test = TRUE)

# Step 1: Get table as matrix, include test statistics
tab_mat <- print(table1, quote = FALSE, noSpaces = TRUE, test = TRUE, printToggle = FALSE)

# Step 2: Convert to data frame and move rownames to a new column
tab_df <- as.data.frame(tab_mat)
tab_df <- tibble::rownames_to_column(tab_df, var = "Variable")

# Step 3: Create and format the flextable

ft <- flextable(tab_df)
ft <- autofit(ft)
ft <- set_table_properties(ft, layout = "autofit")
ft <- fontsize(ft, size = 10, part = "all")
ft <- align(ft, align = "center", part = "all")
ft <- bold(ft, part = "header")

save_as_docx("Balance Table" = ft, path = "balance_table.docx")